import { NestApplication, NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import { Request, Response, NextFunction } from 'express';
import * as cors from 'cors';
import { join } from 'path';
import { CustomResponse } from './common/response';
import { ValidationPipe } from '@nestjs/common';
import { HttpFilter } from './common/filter';
import { RoleGuard } from './users/role.guard';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

const whiteList = ['/users', '/users/create'];
function globalMiddleWare(req: Request, res: Response, next: NextFunction) {
  console.log(req.originalUrl);

  if (whiteList.includes(req.originalUrl)) {
    next();
  } else {
    res.send('全局中间件拦截了');
  }
}

async function bootstrap() {
  const app = await NestFactory.create<NestApplication>(AppModule);
  const options = new DocumentBuilder()
    .setTitle('Nestjs')
    .setDescription('Nestjs description')
    .setVersion('1.0')
    .addTag('Nestjs')
    .build();
  const document = SwaggerModule.createDocument(app, options);
  SwaggerModule.setup('api-docs', app, document);

  app.use(cors());
  // app.use(globalMiddleWare)
  app.useStaticAssets(join(__dirname, 'images'), {
    prefix: '/zz',
  });
  app.useGlobalInterceptors(new CustomResponse());
  app.useGlobalFilters(new HttpFilter());
  app.useGlobalPipes(new ValidationPipe());
  // app.useGlobalGuards(new RoleGuard());
  app.use(
    session({
      secret: 'zhangzheng-secret',
      name: 'zz-session',
      rolling: true,
      cookie: {
        maxAge: null,
      },
    }),
  );
  await app.listen(3000);
}
bootstrap();
